import os
import subprocess
import sys
import time
from typing import Tuple


def run_script(script_name: str) -> Tuple[bool, str]:
    """
    运行指定的 Python 脚本并返回执行结果
    
    Args:
        script_name: 要运行的脚本名称
        
    Returns:
        (是否成功, 输出信息)
    """
    print(f"\n{'=' * 50}")
    print(f"运行脚本: {script_name}")
    print(f"{'=' * 50}")

    try:
        # 运行脚本并捕获输出
        result = subprocess.run(
            [sys.executable, script_name],
            capture_output=True,
            text=True,
            check=True
        )
        return True, result.stdout
    except subprocess.CalledProcessError as e:
        return False, f"错误: {e.stderr}"
    except Exception as e:
        return False, f"未知错误: {str(e)}"


def check_ollama_service() -> bool:
    """检查 Ollama 服务是否正在运行"""
    try:
        import requests
        response = requests.get("http://localhost:11434/api/tags")
        return response.status_code == 200
    except:
        return False


def main():
    """主函数：运行所有测试"""
    # 检查 Ollama 服务
    print("检查 Ollama 服务...")
    if not check_ollama_service():
        print("错误: Ollama 服务未运行！")
        print("请确保 Ollama 服务已启动，并且 Qwen 模型已安装。")
        sys.exit(1)
    print("✓ Ollama 服务正在运行")

    # 要测试的脚本列表
    scripts = [
        "basic_usage.py",
        "chain_examples.py",
        "advanced_features.py"
    ]

    # 运行所有脚本
    results = []
    for script in scripts:
        if not os.path.exists(script):
            print(f"错误: 找不到脚本 {script}")
            continue

        success, output = run_script(script)
        results.append((script, success, output))

        # 在脚本之间添加短暂延迟
        time.sleep(1)

    # 打印测试结果摘要
    print("\n" + "=" * 50)
    print("测试结果摘要")
    print("=" * 50)

    all_passed = True
    for script, success, output in results:
        status = "✓ 通过" if success else "✗ 失败"
        print(f"\n{script}: {status}")
        if not success:
            all_passed = False
            print("错误输出:")
            print(output)

    # 设置退出码
    sys.exit(0 if all_passed else 1)


if __name__ == "__main__":
    main()
